/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-10 11:01:23
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-10 18:16:55
 * @FilePath: /operator-manager/src/pages/AccountAccessManage/components/RoleForm/index.tsx
 * @Description: 角色列表-添加（编辑）角色-角色表单
 */
import { getRoleTreeData } from '@/services';
import { Col, Form, Input, Row, Tree } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { RoleTableEnum } from '../../type.d';
import styles from './index.less';

interface IRoleFormProps {
  initFormValues?: Record<string, any>;
  formKey: number;
}
interface TreeDataNode {
  id: number | string;
  name?: string;
  childrenList?: TreeDataNode[];
}
//获取所有的节点id
const getAllNodeKeys = (data: TreeDataNode[], nodeKeys: React.Key[] = []) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    nodeKeys.push(node.id);
    if (node?.childrenList?.length) {
      getAllNodeKeys(node.childrenList, nodeKeys);
    }
  }
  return nodeKeys;
};

const RoleForm: React.ForwardRefRenderFunction<unknown, IRoleFormProps> = (
  props,
  ref,
) => {
  const { initFormValues, formKey } = props;
  const [form] = Form.useForm();
  const [treeData, setTreeData] = useState([]);
  const [checkedRoleKeys, setCheckedRoleKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);

  // 选中角色所拥有的权限
  const onCheckRole = (checkedKeysValue: React.Key[]) => {
    setCheckedRoleKeys(checkedKeysValue);
    form.setFieldValue(
      [RoleTableEnum.ACCESS_RANGE],
      checkedKeysValue.join(','),
    );
  };
  // 权限树的展开收起
  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
  };
  // 每次获取获取角色树,初始展开所有节点
  const fetchRoleAccessData = () => {
    getRoleTreeData().then((res) => {
      setTreeData(res);
      const expandKeys = getAllNodeKeys(res);
      setExpandedKeys(expandKeys);
      if (initFormValues) {
        // 如果表单的初始值存在，表单需要回显数据
        const currentCheckedKeys = initFormValues?.[RoleTableEnum.ACCESS_RANGE];
        form.setFieldsValue({
          [RoleTableEnum.ROLE_NAME]: initFormValues?.[RoleTableEnum.ROLE_NAME],
          [RoleTableEnum.ROLE_DESC]: initFormValues?.[RoleTableEnum.ROLE_DESC],
          [RoleTableEnum.ACCESS_RANGE]: currentCheckedKeys.join(','),
        });
        setCheckedRoleKeys(currentCheckedKeys);
      } else {
        setCheckedRoleKeys([]);
      }
    });
  };
  useEffect(() => {
    // 获取角色权限树
    fetchRoleAccessData();
  }, [initFormValues]);

  useImperativeHandle(
    ref,
    () => {
      return { roleForm: form };
    },
    [form],
  );
  return (
    <Form layout="horizontal" form={form} key={formKey} name="roleForm">
      <Row>
        <Col span={8}>
          <Form.Item
            label="角色名称"
            name={RoleTableEnum.ROLE_NAME}
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入" maxLength={30} showCount />
          </Form.Item>
        </Col>
        <Col span={8} offset={4}>
          <Form.Item label="角色描述" name={RoleTableEnum.ROLE_DESC}>
            <Input.TextArea placeholder="请输入" maxLength={100} showCount />
          </Form.Item>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Form.Item
            label="角色权限"
            name={RoleTableEnum.ACCESS_RANGE}
            rules={[{ required: true, message: '请选择角色权限' }]}
          >
            <Input hidden />
          </Form.Item>
        </Col>
        <Col span={20}>
          <div className={styles.treeWrapper}>
            <Tree
              blockNode
              checkable
              treeData={treeData}
              onCheck={onCheckRole}
              checkedKeys={checkedRoleKeys}
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              fieldNames={{
                title: 'name',
                key: 'id',
                children: 'childrenList',
              }}
            />
          </div>
        </Col>
      </Row>
    </Form>
  );
};

export default forwardRef(RoleForm);
